<?php
namespace app\api\controller;

use think\Controller;
class LeappayController extends Controller {
    
    protected function initialize(){
	 	parent::initialize();
		header('Access-Control-Allow-Origin:*');
    }

	public function recharge(){
	    $param = input('param.');

	    // 金额
        $amount = (int)$param['amount'];

        //充值方式 银行卡 3  UPI 100
        $payType = $param['payment'];

        //用户id
        $uid = $param['uid'];

        //商户订单号
        $orderNo = $this->getOrderNo('LEAP');

        // 充值时间
        $time = time()-3600;

        //IP
        $data['client_ip'] = $this->getIP();

        //返回格式
        $data['format'] = "page";

        //商品详情
        $data['goods_desc'] = "用户充值";

        //商户号
        $data['mch_id'] = config("app.leappay.mchId");

        //支付金额(卢比)
        $data['money'] = $amount;

        //回调地址
        $data['notify_url'] = $this->getHttpType().$_SERVER['HTTP_HOST']."/api/leappay/notify";
        $data['order_sn'] = $orderNo;
        $data['ptype'] = $payType;
        $data['time'] = $time ;

        //排序
        ksort($data);
        $sign = $this->getSign($data);
        $data['sign'] = $sign;
        print_r($data);

        $posturl = config('app.leappay.rechargeUrl');
        $res = $this->postData($posturl,$data);
        echo $res;

        // 下单
        $json = json_decode($res,true);
        if($json['status'] =="SUCCESS"){
            $res = db('user_recharge')->insert([
                'uid'       => $uid,
                'order_number' => $orderNo,
                'type'       => $payType,
                'money'       => $amount,
                'state'    => 3,
                'add_time'   => time(),
                'postscript'  => $param['name'],
                'bank_code'  => 'leappay-3'
            ]);

            header('Location:'.$json['order_data']);
            exit;
        }else{
            return json(['code'=>1,'info'=>'ERROR_CODE:'.$json['err_code'].",ERROR_MSG:".$json['err_msg']]);
        }
	}
	
    public function notify(){
        $param = input('param.');
        $sign = $param['sign'];
        unset($param['sign']);
        $notifySign = $this->getSign($param);
        if($notifySign == $sign){

            //商户系统业务单号
            $sh_order = $param['sh_order'];

            //订单状态
            $state = $param['state'];

            // 订单状态
            //0已提交   1已接单  2超时补单   3订单失败  4交易完成   5未接单
            if($state==4){
                $res = db('user_recharge')->where('order_number',$param['sh_order'])->where('state',3)->update(['daozhang_money'=>$param['money'],'endtime'=>time(),'state'=>1]);
                $order = db('user_recharge')->where('order_number',$param['sh_order'])->find();
                $is_updata_user = db('user_total')->where('uid' , $order['uid'])->setInc('balance', $param['money'])->setInc('total_recharge',$param['money'])->setInc('total_balance',$param['money']);
            }else{
                $file = file_put_contents('./india_notify.log',"回调通知，订单未交易成功，回调状态为：".$state."\r\n",FILE_APPEND);
            }

        }else{
            $file = file_put_contents('./india_notify.log',"签名失败"."\r\n",FILE_APPEND);
        }
        die('success');exit;

    }


    /*
     * 获取IP
     */
    public function getIP(){
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP") , "unknown")) {
	        $ip = getenv("HTTP_CLIENT_IP");
	    } else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR") , "unknown")) {
	        $ip = getenv("HTTP_X_FORWARDED_FOR");
	    } else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR") , "unknown")) {
	        $ip = getenv("REMOTE_ADDR");
	    } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
	        $ip = $_SERVER['REMOTE_ADDR'];
	    } else {
	        $ip = "unknown";
	    }
	    return $ip;
	}
    /*
     * 生成订单号
     */
    public function getOrderNo($str){
        return $str.date('YmdHis').rand(100,999);
    }

    /*
     * 签名
     */
    public function getSign($data){
        ksort($data);
        $secretKey = config('app.leappay.secretKey');
        $str = '';
        foreach($data as $k=>$v){
            $str .= $k."=".$v. "&";
        }
        $str .= "key=".$secretKey;
        $sign = md5($str);
        return$sign; 
    }

    public function postData($url,$data){
        $curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($curl, CURLOPT_TIMEOUT, 300);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$response = curl_exec($curl);
		$curl_errno = curl_errno($curl);
		$curl_error = curl_error($curl);
		curl_close($curl);
		return $response;
    }

    /*
     * 判断HTTP HTTPS方法
     */
    public function getHttpType(){
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        return $http_type; 
    }
	
	



  
   
        
}
